// 定时器
let taskTimers = []
// 提醒数量
let badge = 0

/**
 * 提醒
 */
function notice(noticeId, options) {
  let opt = {
    iconUrl: 'images/logo.128.png',
    type: 'basic',
    title: '浪潮小助手提醒',
    eventTime: new Date().getTime(),
    requireInteraction: true
  }
  chrome.notifications.create(noticeId, Object.assign(opt, options));
}


/**
 * 刷新当天提醒
 */
function reloadTask () {
  if (localStorage.__task) {
    let taskState = JSON.parse(localStorage.__task)

    let now = new Date()
    let today = now.format('yyyy-MM-dd')
    let timestamp = now.getTime()

    let unFinishTasks = taskState.tasks
      .filter(task => task && !task.isFinish)
      .map(task => {
        return { timeout: new Date(`${today} ${task.time}`).getTime() - timestamp, ... task}
      })

    if (taskTimers && taskTimers.length) {
      taskTimers.forEach(clearTimeout)
    }

    taskTimers = unFinishTasks.filter(task => task.timeout > 0)
      .map(task => {
        return setTimeout(function (t) {
          let noticeId = `${t.title}-${t.time}`
          notice(noticeId, {
            message: `${t.time} 该${t.title}了`
          })

          incBadge(1)
        }, task.timeout, task)
      })

    console.log(`${new Date().format('yyyy-MM-dd HH:mm:ss')}加载定时器:`, taskTimers)

    badge = unFinishTasks.filter(x => x.timeout <= 0).length
    incBadge(0)
  }
}

/**
 * 创建今天的任务
 */
function createTodayTask () {
  if (localStorage.__task) {
    let state = JSON.parse(localStorage.__task)

    let now = new Date()
    let today = now.format('yyyy-MM-dd')
    let weekDay = now.getDay()

    if (state.taskDate !== today && now.getHours() > 4) {

      state.tasks = state.taskTemplates
        .filter(x => x.cycleType === 'day' || (x.cycleType === 'week' && x.weekDay === weekDay))
        .map(x => {
          return {title: x.title, time: x.time, isFinish: false}
        })

      state.taskDate = today
      localStorage.__task = JSON.stringify(state)
    }
    reloadTask()
  }
}

/**
 * 通知数更新
 * @param num 增量
 */
function incBadge (num) {
  badge += num
  chrome.browserAction.setBadgeText({ text: (badge > 0 ? badge.toString() : '') })
}


chrome.runtime.onMessage.addListener((message) => {
  switch (message.type) {
    case 'flushTask': 
      reloadTask()
      break
    case 'badge':
      incBadge.incBadge(message.count)
      break
    case 'notice':
      notice('id-' + new Date().getTime(), message.notice)
      break
  }
});

/**
 * 为日期对象增加函数
 * 日期格式化
 * 格式 YYYY/yyyy/YY/yy 表示年份
 * MM/M 月份
 * W/w 星期
 * dd/DD/d/D 日期
 * hh/HH/h/H 时间
 * mm/m 分钟
 * ss/SS/s/S 秒
 * @param {String} formatStr 日期格式字符串
 */
Date.prototype.format = function(formatStr)
{
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    var month = this.getMonth() + 1;
    str = str.replace(/MM/, month > 9 ? month.toString() : '0' + month);
    str = str.replace(/M/g, month);

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
};

//运行时加载提醒任务
setInterval(createTodayTask, 5 * 60 * 1000)

//初次加载
createTodayTask()
